let currentFolderId = '1';
let breadcrumbPath = [];
let searchTimeout = null;
let allBookmarks = [];

document.addEventListener('DOMContentLoaded', () => {
    loadBookmarks(currentFolderId);
    
    // 初始化搜索功能
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');
    
    // 加载所有书签数据
    chrome.bookmarks.getTree((bookmarkTreeNodes) => {
        allBookmarks = [];
        traverseBookmarks(bookmarkTreeNodes[0], [], allBookmarks);
    });
    
    // 添加搜索输入事件
    searchInput.addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        const query = e.target.value.trim();
        
        if (query === '') {
            searchResults.style.display = 'none';
            return;
        }
        
        searchTimeout = setTimeout(() => {
            searchBookmarks(query);
        }, 300);
    });
    
    // 点击外部关闭搜索结果
    document.addEventListener('click', (e) => {
        if (!searchResults.contains(e.target) && e.target !== searchInput) {
            searchResults.style.display = 'none';
        }
    });
    
    // 初始化日期时间显示
    initDateTime();
    
    // 添加导入导出功能
    initImportExport();
});

function loadBookmarks(folderId) {
    // 如果是根目录且导航路径为空，初始化导航路径
    if (folderId === '1') {
        chrome.bookmarks.get(folderId, (nodes) => {
            if (breadcrumbPath.length === 0) {
                breadcrumbPath = [{
                    id: '1',
                    title: '首页'
                }];
            }
            // 获取并显示书签
            chrome.bookmarks.getChildren(folderId, loadBookmarksContent);
        });
    } else {
        // 如果不是根目录，先获取当前文件夹信息
        chrome.bookmarks.get(folderId, (nodes) => {
            const currentFolder = nodes[0];
            // 如果点击的是新文件夹（不在导航路径中）
            if (!breadcrumbPath.find(item => item.id === currentFolder.id)) {
                breadcrumbPath.push({
                    id: currentFolder.id,
                    title: currentFolder.title
                });
            }
            // 获取并显示书签
            chrome.bookmarks.getChildren(folderId, loadBookmarksContent);
        });
    }
}

// 将书签加载逻辑抽离成单独的函数
function loadBookmarksContent(bookmarkNodes) {
    const container = document.getElementById('bookmarks-container');
    container.innerHTML = '';
    
    // 创建书签容器和分类容器
    const bookmarksContainer = document.createElement('div');
    bookmarksContainer.className = 'bookmarks-list';
    
    const foldersContainer = document.createElement('div');
    foldersContainer.className = 'folders-grid';
    
    // 分离书签和文件夹
    const bookmarks = bookmarkNodes.filter(node => node.url);
    const folders = bookmarkNodes.filter(node => !node.url);
    
    // 创建书签区域
    const bookmarksSection = document.createElement('div');
    bookmarksSection.className = 'section';
    
    // 显示书签
    if (bookmarks.length > 0 || true) {
        const bookmarksTitle = document.createElement('h2');
        bookmarksTitle.className = 'section-title';
        bookmarksTitle.textContent = '书签列表';
        bookmarksSection.appendChild(bookmarksTitle);
        bookmarksSection.appendChild(bookmarksContainer);
    }
    
    bookmarks.forEach(bookmark => {
        const bookmarkItem = createBookmarkItem(bookmark);
        bookmarksContainer.appendChild(bookmarkItem);
    });
    
    // 添加"新增书签"按钮
    const newBookmarkButton = document.createElement('div');
    newBookmarkButton.className = 'bookmark-item create-bookmark';
    newBookmarkButton.innerHTML = `
        <div class="bookmark-content">
            <i class="fas fa-plus"></i>
            <span>新增书签</span>
        </div>
    `;
    newBookmarkButton.addEventListener('click', () => {
        createNewBookmark(currentFolderId);
    });
    bookmarksContainer.appendChild(newBookmarkButton);
    
    // 创建分类区域
    const foldersSection = document.createElement('div');
    foldersSection.className = 'section';
    
    // 显示文件夹
    if (folders.length > 0) {
        const foldersTitle = document.createElement('h2');
        foldersTitle.className = 'section-title';
        foldersTitle.textContent = '分类列表';
        foldersSection.appendChild(foldersTitle);
        foldersSection.appendChild(foldersContainer);
    }
    
    folders.forEach(folder => {
        const folderCard = createFolderCard(folder);
        foldersContainer.appendChild(folderCard);
    });
    
    // 添加"新建分类"按钮
    const newFolderButton = document.createElement('div');
    newFolderButton.className = 'folder-card create-folder';
    newFolderButton.innerHTML = `<h3>+ 新建分类</h3>`;
    newFolderButton.addEventListener('click', () => {
        createNewFolder(currentFolderId);
    });
    foldersContainer.appendChild(newFolderButton);
    
    // 将区域添加到主容器
    container.appendChild(bookmarksSection);
    container.appendChild(foldersSection);
    
    // 初始化书签和分类的拖拽排序
    initSortable(bookmarksContainer, currentFolderId, 'bookmark');
    initSortable(foldersContainer, currentFolderId, 'folder');
    
    // 更新导航栏
    updateBreadcrumb();
}

function createFolderCard(folder) {
    const card = document.createElement('div');
    card.className = 'folder-card';
    card.dataset.folderId = folder.id;  // 添加文件夹ID属性
    
    // 设置渐变背景
    const gradient = getRandomPastelColor();
    card.style.background = gradient;
    
    // 创建标题容器
    const titleContainer = document.createElement('div');
    titleContainer.className = 'folder-title-container';
    
    // 创建图标和标题区域
    const titleArea = document.createElement('div');
    titleArea.className = 'title-area';
    
    // 添加文件夹图标
    const folderIcon = document.createElement('i');
    folderIcon.className = 'fas fa-folder';
    // 设置图标颜色为主题色
    folderIcon.style.color = '#2196F3';  // 使用蓝色作为文件夹图标的颜色
    
    const title = document.createElement('h3');
    title.textContent = folder.title;
    
    titleArea.appendChild(folderIcon);
    titleArea.appendChild(title);
    
    // 创建按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'button-container';
    
    // 创建编辑按钮
    const editButton = document.createElement('button');
    editButton.className = 'folder-button edit-button';
    editButton.innerHTML = '✎';
    editButton.title = '编辑分类名称';
    editButton.onclick = (e) => {
        e.stopPropagation();
        editFolderName(folder, title);
    };
    
    // 创建删除按钮
    const deleteButton = document.createElement('button');
    deleteButton.className = 'folder-button delete-button';
    deleteButton.innerHTML = '×';
    deleteButton.title = '删除分类';
    deleteButton.onclick = (e) => {
        e.stopPropagation();
        deleteFolder(folder);
    };
    
    buttonContainer.appendChild(editButton);
    buttonContainer.appendChild(deleteButton);
    titleContainer.appendChild(titleArea);
    titleContainer.appendChild(buttonContainer);
    
    // 创建统计信息容器
    const statsContainer = document.createElement('div');
    statsContainer.className = 'folder-stats';
    
    // 获取子文件夹和书签数量
    chrome.bookmarks.getChildren(folder.id, (children) => {
        const subfolders = children.filter(node => !node.url);
        const bookmarks = children.filter(node => node.url);
        
        statsContainer.innerHTML = `
            <span class="stat-item">
                <i class="fas fa-folder-open" style="color: #1976D2"></i> ${subfolders.length} 个子分类
            </span>
            <span class="stat-item">
                <i class="fas fa-bookmark" style="color: #4CAF50"></i> ${bookmarks.length} 个书签
            </span>
        `;
    });
    
    card.appendChild(titleContainer);
    card.appendChild(statsContainer);
    
    card.addEventListener('click', (e) => {
        // 阻止事件冒泡，避免与拖拽冲突
        if (e.target.closest('.button-container')) {
            return;
        }
        
        currentFolderId = folder.id;
        loadBookmarks(folder.id);
    });
    
    return card;
}

function createBookmarkItem(bookmark) {
    const item = document.createElement('div');
    item.className = 'bookmark-item';
    item.dataset.bookmarkId = bookmark.id;
    
    // 添加渐变边框
    const borderGradient = getRandomBorderGradient();
    item.style.borderImage = `${borderGradient} 1`;
    item.style.borderImageSlice = '1';
    
    // 创建带图标的链接
    const link = document.createElement('a');
    link.href = bookmark.url;
    
    try {
        // 尝试获取网站域名
        const url = new URL(bookmark.url);
        // 创建favicon图片元素
        const faviconImg = document.createElement('img');
        faviconImg.className = 'favicon';
        faviconImg.src = `${url.protocol}//${url.hostname}/favicon.ico`;
        faviconImg.addEventListener('error', () => {
            faviconImg.src = 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🔖</text></svg>';
        });
        
        const titleSpan = document.createElement('span');
        titleSpan.textContent = bookmark.title;
        
        link.appendChild(faviconImg);
        link.appendChild(titleSpan);
    } catch (e) {
        link.innerHTML = `
            <i class="fas fa-bookmark"></i>
            <span>${bookmark.title}</span>
        `;
    }
    
    // 修改点击事件处理
    item.addEventListener('mousedown', function(e) {
        // 存储点击时的时间戳
        this.mouseDownTime = Date.now();
    });
    
    item.addEventListener('mouseup', function(e) {
        // 如果点击时间小于200ms，认为是点击而不是拖动
        if (Date.now() - this.mouseDownTime < 200) {
            // 确保不是点击编辑或删除按钮
            if (!e.target.closest('.bookmark-actions')) {
                window.open(bookmark.url, '_blank');
            }
        }
    });
    
    // 创建操作按钮容器
    const actions = document.createElement('div');
    actions.className = 'bookmark-actions';
    
    // 创建编辑按钮
    const editButton = document.createElement('button');
    editButton.className = 'bookmark-action-button bookmark-edit-button';
    editButton.innerHTML = '✎';
    editButton.title = '编辑书签';
    editButton.onclick = (e) => {
        e.preventDefault();
        e.stopPropagation();
        editBookmark(bookmark, link);
    };
    
    // 创建删除按钮
    const deleteButton = document.createElement('button');
    deleteButton.className = 'bookmark-action-button bookmark-delete-button';
    deleteButton.innerHTML = '×';
    deleteButton.title = '删除书签';
    deleteButton.onclick = (e) => {
        e.preventDefault();
        e.stopPropagation();
        deleteBookmark(bookmark);
    };
    
    actions.appendChild(editButton);
    actions.appendChild(deleteButton);
    item.appendChild(link);
    item.appendChild(actions);
    
    return item;
}

// 添加编辑书签的函数
function editBookmark(bookmark, linkElement) {
    // 创建编辑对话框
    const dialog = document.createElement('div');
    dialog.className = 'edit-dialog';
    dialog.innerHTML = `
        <div class="edit-dialog-content">
            <h3>编辑书签</h3>
            <div class="edit-form">
                <div class="form-group">
                    <label>名称:</label>
                    <input type="text" id="editTitle" value="${bookmark.title}">
                </div>
                <div class="form-group">
                    <label>网址:</label>
                    <input type="url" id="editUrl" value="${bookmark.url}">
                </div>
                <div class="dialog-buttons">
                    <button class="save-button">保存</button>
                    <button class="cancel-button">取消</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(dialog);
    
    // 获取对话框中的元素
    const titleInput = dialog.querySelector('#editTitle');
    const urlInput = dialog.querySelector('#editUrl');
    const saveButton = dialog.querySelector('.save-button');
    const cancelButton = dialog.querySelector('.cancel-button');
    
    // 保存按钮点击事件
    saveButton.onclick = () => {
        const newTitle = titleInput.value.trim();
        const newUrl = urlInput.value.trim();
        
        if (newTitle && newUrl) {
            chrome.bookmarks.update(bookmark.id, {
                title: newTitle,
                url: newUrl
            }, (updatedBookmark) => {
                // 更新bookmark对象
                bookmark.title = newTitle;
                bookmark.url = newUrl;
                
                // 更新界面显示
                linkElement.href = newUrl;
                linkElement.innerHTML = `
                    <i class="fas fa-bookmark"></i>
                    <span>${newTitle}</span>
                `;
                
                // 更新搜索结果中的数据
                const bookmarkIndex = allBookmarks.findIndex(item => item.id === bookmark.id);
                if (bookmarkIndex !== -1) {
                    allBookmarks[bookmarkIndex].title = newTitle;
                    allBookmarks[bookmarkIndex].url = newUrl;
                }
                
                // 关闭对话框
                document.body.removeChild(dialog);
            });
        }
    };
    
    // 取消按钮点击事件
    cancelButton.onclick = () => {
        document.body.removeChild(dialog);
    };
    
    // 点击对话框外部关闭
    dialog.onclick = (e) => {
        if (e.target === dialog) {
            document.body.removeChild(dialog);
        }
    };
    
    // 聚焦到标题输入框
    titleInput.focus();
    titleInput.select();
}

function updateBreadcrumb() {
    const breadcrumb = document.getElementById('breadcrumb');
    breadcrumb.innerHTML = '';
    
    breadcrumbPath.forEach((item, index) => {
        const breadcrumbItem = document.createElement('span');
        breadcrumbItem.className = 'breadcrumb-item';
        breadcrumbItem.textContent = item.title;
        breadcrumbItem.addEventListener('click', () => {
            // 点击导航项时，截断到当前位置并导航
            breadcrumbPath = breadcrumbPath.slice(0, index + 1);
            loadBookmarks(item.id);
        });
        
        breadcrumb.appendChild(breadcrumbItem);
    });
}

function getRandomPastelColor() {
    const gradients = [
        // 柔和的蓝色系列
        'linear-gradient(135deg, #E3F2FD, #90CAF9)',  // 淡蓝
        'linear-gradient(135deg, #E8EAF6, #C5CAE9)',  // 靛蓝
        'linear-gradient(135deg, #E1F5FE, #81D4FA)',  // 天蓝
        'linear-gradient(135deg, #EDE7F6, #B39DDB)',  // 淡紫
        
        // 柔和的青色系列
        'linear-gradient(135deg, #E0F7FA, #80DEEA)',  // 青色
        'linear-gradient(135deg, #F1F8E9, #C5E1A5)',  // 青柠
        'linear-gradient(135deg, #E0F2F1, #80CBC4)',  // 蒂芙尼
        'linear-gradient(135deg, #E8F5E9, #A5D6A7)',  // 薄荷
        
        // 柔和的灰色系列
        'linear-gradient(135deg, #ECEFF1, #B0BEC5)',  // 蓝灰
        'linear-gradient(135deg, #FAFAFA, #EEEEEE)',  // 纯灰
        'linear-gradient(135deg, #F5F5F5, #E0E0E0)',  // 珍珠灰
        'linear-gradient(135deg, #EFEBE9, #D7CCC8)',  // 暖灰
        
        // 柔和的紫色系列
        'linear-gradient(135deg, #F3E5F5, #CE93D8)',  // 淡紫
        'linear-gradient(135deg, #EDE7F6, #B39DDB)',  // 薰衣草
        'linear-gradient(135deg, #E8EAF6, #9FA8DA)',  // 紫罗兰
        
        // 柔和的绿色系列
        'linear-gradient(135deg, #E8F5E9, #A5D6A7)',  // 薄荷绿
        'linear-gradient(135deg, #F1F8E9, #C5E1A5)',  // 嫩绿
        'linear-gradient(135deg, #E0F2F1, #80CBC4)'   // 青绿
    ];
    
    const randomGradient = gradients[Math.floor(Math.random() * gradients.length)];
    return `${randomGradient}`;
}

// 添加创建新文件夹的函数
function createNewFolder(parentId) {
    const folderName = prompt('请输入分类名称：');
    if (folderName) {
        chrome.bookmarks.create({
            'parentId': parentId,
            'title': folderName
        }, (newFolder) => {
            // 创建成功后重新加载当前文件夹
            loadBookmarks(parentId);
        });
    }
}

// 添加编辑文件夹名称的函数
function editFolderName(folder, titleElement) {
    const newName = prompt('请输入新的分类名称：', folder.title);
    if (newName && newName !== folder.title) {
        chrome.bookmarks.update(folder.id, {
            'title': newName
        }, (updatedFolder) => {
            titleElement.textContent = newName;
            // 更新面包屑导航中的名称
            const breadcrumbIndex = breadcrumbPath.findIndex(item => item.id === folder.id);
            if (breadcrumbIndex !== -1) {
                breadcrumbPath[breadcrumbIndex].title = newName;
                updateBreadcrumb();
            }
        });
    }
}

// 添加删除文件夹的函数
function deleteFolder(folder) {
    if (confirm(`确定要删除分类"${folder.title}"吗？\n注意：该分类下的所有子分类和书签都将被删除！`)) {
        chrome.bookmarks.removeTree(folder.id, () => {
            // 如果删除的是当前文件夹，返回上一级
            if (folder.id === currentFolderId) {
                const parentId = breadcrumbPath.length > 1 
                    ? breadcrumbPath[breadcrumbPath.length - 2].id 
                    : '1';
                currentFolderId = parentId;
                breadcrumbPath.pop();
                loadBookmarks(parentId);
            } else {
                // 否则刷新当前文件夹
                loadBookmarks(currentFolderId);
            }
        });
    }
}

// 修改遍历书签的函数
function traverseBookmarks(node, path, results) {
    // 跳过根节点和书签栏节点的标题
    const currentPath = node.id === '0' || node.id === '1' ? 
        path : [...path, node.title];
    
    if (node.children) {
        // 这是一个文件夹
        if (node.id !== '0' && node.id !== '1') {  // 排除根节点和书签栏
            results.push({
                id: node.id,
                title: node.title,
                path: currentPath,
                type: 'folder'
            });
        }
        // 递归处理子节点
        node.children.forEach(child => traverseBookmarks(child, currentPath, results));
    } else if (node.url) {
        // 这是一个书签
        results.push({
            id: node.id,
            title: node.title,
            url: node.url,
            path: currentPath,
            type: 'bookmark'
        });
    }
}

// 修改搜索函数
function searchBookmarks(query) {
    query = query.toLowerCase();
    
    // 过滤匹配的书签和文件夹
    const results = allBookmarks.filter(item => {
        const titleMatch = item.title.toLowerCase().includes(query);
        const urlMatch = item.url && item.url.toLowerCase().includes(query);
        return titleMatch || urlMatch;
    });

    const searchResults = document.getElementById('searchResults');
    searchResults.innerHTML = '';

    // 分离文件夹和书签
    const folders = results.filter(item => item.type === 'folder');
    const bookmarks = results.filter(item => item.type === 'bookmark');

    // 添加文件夹结果
    if (folders.length > 0) {
        const folderGroup = document.createElement('div');
        folderGroup.className = 'search-result-group';
        folderGroup.innerHTML = `<i class="fas fa-folder"></i>分类 (${folders.length})`;
        searchResults.appendChild(folderGroup);

        folders.forEach(folder => {
            const resultItem = document.createElement('div');
            resultItem.className = 'search-result-item';
            resultItem.dataset.id = folder.id;
            resultItem.dataset.type = 'folder';
            
            resultItem.innerHTML = `
                <i class="fas fa-folder" style="color: #2196F3"></i>
                <span class="title">${folder.title}</span>
                <span class="url">${folder.path.slice(1).join(' > ')}</span>
            `;
            
            searchResults.appendChild(resultItem);
        });
    }

    // 添加书签结果
    if (bookmarks.length > 0) {
        const bookmarkGroup = document.createElement('div');
        bookmarkGroup.className = 'search-result-group';
        bookmarkGroup.innerHTML = `<i class="fas fa-bookmark"></i>书签 (${bookmarks.length})`;
        searchResults.appendChild(bookmarkGroup);

        bookmarks.forEach(bookmark => {
            const resultItem = document.createElement('div');
            resultItem.className = 'search-result-item';
            resultItem.dataset.id = bookmark.id;
            resultItem.dataset.type = 'bookmark';
            resultItem.dataset.url = bookmark.url;

            try {
                const urlObj = new URL(bookmark.url);
                const img = document.createElement('img');
                img.className = 'favicon';
                img.src = `${urlObj.protocol}//${urlObj.hostname}/favicon.ico`;
                img.addEventListener('error', () => {
                    img.src = 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🔖</text></svg>';
                });
                resultItem.appendChild(img);
            } catch (e) {
                const icon = document.createElement('i');
                icon.className = 'fas fa-bookmark';
                resultItem.appendChild(icon);
            }

            const title = document.createElement('span');
            title.className = 'title';
            title.textContent = bookmark.title;
            resultItem.appendChild(title);

            const path = document.createElement('span');
            path.className = 'url';
            path.textContent = bookmark.path.slice(1).join(' > ');
            resultItem.appendChild(path);

            searchResults.appendChild(resultItem);
        });
    }

    // 如果没有结果
    if (results.length === 0) {
        const emptyResult = document.createElement('div');
        emptyResult.className = 'search-result-empty';
        emptyResult.innerHTML = `
            <i class="fas fa-search"></i>
            <p>未找到匹配的结果</p>
        `;
        searchResults.appendChild(emptyResult);
    }

    // 显示搜索结果
    if (results.length > 0 || query) {
        searchResults.style.display = 'block';
        setTimeout(() => {
            searchResults.classList.add('show');
        }, 10);
    } else {
        hideSearchResults();
    }

    // 添加点击事件处理
    searchResults.querySelectorAll('.search-result-item').forEach(item => {
        item.addEventListener('click', () => {
            const type = item.dataset.type;
            const id = item.dataset.id;
            
            if (type === 'folder') {
                navigateToFolder(id);
                hideSearchResults();
            } else {
                window.open(item.dataset.url, '_blank');
            }
            
            // 清空搜索框
            document.getElementById('searchInput').value = '';
        });
    });
}

// 修改获取网站图标的函数
function getFaviconHtml(url) {
    try {
        const urlObj = new URL(url);
        const img = document.createElement('img');
        img.className = 'favicon';
        img.src = `${urlObj.protocol}//${urlObj.hostname}/favicon.ico`;
        
        // 使用 addEventListener 替代 onerror
        img.addEventListener('error', () => {
            img.src = 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🔖</text></svg>';
        });
        
        const container = document.createElement('div');
        container.appendChild(img);
        return container.innerHTML;
    } catch (e) {
        return '<i class="fas fa-bookmark"></i>';
    }
}

// 修改搜索结果项的创建方式
function createSearchResultItem(item) {
    const resultItem = document.createElement('div');
    resultItem.className = 'search-result-item';
    resultItem.dataset.id = item.id;
    resultItem.dataset.type = item.url ? 'bookmark' : 'folder';
    if (item.url) {
        resultItem.dataset.url = item.url;
    }

    if (item.url) {
        // 为书签创建图标
        try {
            const urlObj = new URL(item.url);
            const img = document.createElement('img');
            img.className = 'favicon';
            img.src = `${urlObj.protocol}//${urlObj.hostname}/favicon.ico`;
            img.addEventListener('error', () => {
                img.src = 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🔖</text></svg>';
            });
            resultItem.appendChild(img);
        } catch (e) {
            const icon = document.createElement('i');
            icon.className = 'fas fa-bookmark';
            resultItem.appendChild(icon);
        }
    } else {
        // 为文件夹创建图标
        const icon = document.createElement('i');
        icon.className = 'fas fa-folder';
        icon.style.color = '#2196F3';
        resultItem.appendChild(icon);
    }

    const title = document.createElement('span');
    title.className = 'title';
    title.textContent = item.title;
    resultItem.appendChild(title);

    const path = document.createElement('span');
    path.className = 'url';
    path.textContent = item.path.slice(1).join(' > ');
    resultItem.appendChild(path);

    return resultItem;
}

// 为搜索结果添加事件监听器
function attachSearchResultsEvents(searchResults) {
    searchResults.querySelectorAll('.search-result-item').forEach(item => {
        item.addEventListener('click', () => {
            const type = item.dataset.type;
            const id = item.dataset.id;
            
            if (type === 'folder') {
                navigateToFolder(id);
                hideSearchResults();
            } else {
                window.open(item.dataset.url, '_blank');
            }
        });
    });
}

// 显示搜索结果
function showSearchResults(searchResults) {
    searchResults.style.display = 'block';
    setTimeout(() => {
        searchResults.classList.add('show');
    }, 10);
}

// 隐藏搜索结果
function hideSearchResults() {
    const searchResults = document.getElementById('searchResults');
    searchResults.classList.remove('show');
    setTimeout(() => {
        searchResults.style.display = 'none';
    }, 300);
}

// 导航到指定文件夹
function navigateToFolder(folderId) {
    // 重置导航路径
    breadcrumbPath = [];
    
    // 递归查找文件夹路径
    function findFolderPath(id, callback) {
        chrome.bookmarks.get(id, (nodes) => {
            if (nodes[0].parentId === '0' || nodes[0].parentId === '1') {
                callback([]);
            } else {
                findFolderPath(nodes[0].parentId, (parentPath) => {
                    callback([...parentPath, {
                        id: nodes[0].id,
                        title: nodes[0].title
                    }]);
                });
            }
        });
    }
    
    findFolderPath(folderId, (path) => {
        breadcrumbPath = path;
        currentFolderId = folderId;
        loadBookmarks(folderId);
    });
}

// 添加删除书签的函数
function deleteBookmark(bookmark) {
    if (confirm(`确定要删除书签"${bookmark.title}"吗？`)) {
        chrome.bookmarks.remove(bookmark.id, () => {
            // 删除成功后重新加载当前文件夹
            loadBookmarks(currentFolderId);
        });
    }
}

// 初始化日期时间显示
function initDateTime() {
    updateDateTime();
    setInterval(updateDateTime, 1000);
}

// 更新日期时间
function updateDateTime() {
    const now = new Date();
    const timeElement = document.querySelector('.time');
    const dateElement = document.querySelector('.date');
    
    // 更新时间
    timeElement.textContent = now.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    
    // 更新公历日期
    dateElement.textContent = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
    });
    
    // 更新农历日期
    const lunar = new Lunar(now);
    const lunarDate = lunar.getLunarDate();
    
    // 如果农历日期元素不存在则创建
    let lunarElement = document.querySelector('.lunar-date');
    if (!lunarElement) {
        lunarElement = document.createElement('div');
        lunarElement.className = 'lunar-date';
        document.querySelector('.datetime-container').appendChild(lunarElement);
    }
    
    // 更新农历日期显示
    lunarElement.textContent = `农历 ${lunarDate.yearCn} ${lunarDate.monthCn}${lunarDate.dayCn}`;
}

// 添加初始化拖拽排序的函数
function initSortable(container, parentId, type) {
    new Sortable(container, {
        animation: 150,
        handle: type === 'folder' ? '.folder-card' : '.bookmark-item',
        filter: '.create-folder, .create-bookmark',  // 排除新建按钮
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        dragClass: 'sortable-drag',
        group: type,
        
        onEnd: function(evt) {
            if (type === 'folder') {
                const folderCards = Array.from(container.children)
                    .filter(el => !el.classList.contains('create-folder'));
                updateBookmarkOrder(folderCards, parentId, type);
            } else {
                const bookmarkItems = Array.from(container.children)
                    .filter(el => !el.classList.contains('create-bookmark'));
                updateBookmarkOrder(bookmarkItems, parentId, type);
            }
        }
    });
}

// 添加更新书签顺序的函数
function updateBookmarkOrder(items, parentId, type) {
    // 获取所有项目的ID
    const itemIds = items.map(item => 
        type === 'folder' ? item.dataset.folderId : item.dataset.bookmarkId
    );
    
    // 递归更新顺序
    function moveItem(index) {
        if (index >= itemIds.length) {
            // 所有移动完成后重新加载
            loadBookmarks(parentId);
            return;
        }
        
        const itemId = itemIds[index];
        chrome.bookmarks.move(itemId, {
            parentId: parentId,
            index: index
        }, () => {
            moveItem(index + 1);
        });
    }
    
    moveItem(0);
}

// 添加导入导出功能
function initImportExport() {
    // 创建隐藏的文件输入框
    const importInput = document.createElement('input');
    importInput.type = 'file';
    importInput.id = 'importInput';
    importInput.accept = '.html';
    document.body.appendChild(importInput);
    
    // 导入按钮点击事件
    const importButton = document.querySelector('.import-button');
    importButton.addEventListener('click', () => {
        importInput.click();
    });
    
    // 文件选择事件
    importInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                importBookmarks(e.target.result);
            };
            reader.readAsText(file);
        }
    });
    
    // 导出按钮点击事件
    const exportButton = document.querySelector('.export-button');
    exportButton.addEventListener('click', exportBookmarks);
}

// 导入书签函数
function importBookmarks(htmlContent) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlContent, 'text/html');
    const bookmarks = [];
    
    // 递归解析书签
    function parseBookmarks(element, parentId) {
        const items = element.children;
        for (let item of items) {
            if (item.tagName === 'A') {
                bookmarks.push({
                    parentId: parentId,
                    title: item.textContent,
                    url: item.href
                });
            } else if (item.tagName === 'H3') {
                // 创建新文件夹
                chrome.bookmarks.create({
                    parentId: parentId,
                    title: item.textContent
                }, (newFolder) => {
                    if (item.nextElementSibling && item.nextElementSibling.tagName === 'DL') {
                        parseBookmarks(item.nextElementSibling, newFolder.id);
                    }
                });
            } else if (item.tagName === 'DL') {
                parseBookmarks(item, parentId);
            }
        }
    }
    
    // 开始解析
    const bookmarkList = doc.querySelector('DL');
    if (bookmarkList) {
        chrome.bookmarks.getChildren('1', (existingBookmarks) => {
            if (confirm('导入将合并到现有书签中，是否继续？')) {
                parseBookmarks(bookmarkList, '1');
                setTimeout(() => {
                    loadBookmarks('1');
                    alert('书签导入完成！');
                }, 1000);
            }
        });
    } else {
        alert('无效的书签文件！');
    }
}

// 导出书签函数
function exportBookmarks() {
    chrome.bookmarks.getTree((bookmarkTree) => {
        let html = '<!DOCTYPE NETSCAPE-Bookmark-file-1>\n' +
                  '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">\n' +
                  '<TITLE>Bookmarks</TITLE>\n' +
                  '<H1>Bookmarks</H1>\n<DL><p>\n';
        
        // 递归生成书签HTML
        function generateBookmarkHTML(nodes, level) {
            let indent = '    '.repeat(level);
            for (let node of nodes) {
                if (node.children) {
                    html += `${indent}<DT><H3>${node.title}</H3>\n`;
                    html += `${indent}<DL><p>\n`;
                    generateBookmarkHTML(node.children, level + 1);
                    html += `${indent}</DL><p>\n`;
                } else if (node.url) {
                    html += `${indent}<DT><A HREF="${node.url}">${node.title}</A>\n`;
                }
            }
        }
        
        generateBookmarkHTML(bookmarkTree[0].children, 1);
        html += '</DL><p>';
        
        // 创建并下载文件
        const blob = new Blob([html], { type: 'text/html' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `bookmarks_${new Date().toISOString().slice(0,10)}.html`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    });
}

// 修改创建新书签的函数
function createNewBookmark(folderId) {
    const dialog = document.getElementById('bookmarkDialog');
    const form = document.getElementById('bookmarkForm');
    const titleInput = document.getElementById('bookmarkTitle');
    const urlInput = document.getElementById('bookmarkUrl');
    
    // 显示弹窗
    dialog.classList.add('show');
    
    // 聚焦到标题输入框
    titleInput.focus();
    
    // 取消按钮事件
    dialog.querySelector('.cancel-button').onclick = () => {
        dialog.classList.remove('show');
        form.reset();
    };
    
    // 点击遮罩层关闭
    dialog.onclick = (e) => {
        if (e.target === dialog) {
            dialog.classList.remove('show');
            form.reset();
        }
    };
    
    // 表单提交事件
    form.onsubmit = (e) => {
        e.preventDefault();
        
        const title = titleInput.value.trim();
        const url = urlInput.value.trim();
        
        try {
            new URL(url);
            // 创建新书签
            chrome.bookmarks.create({
                parentId: folderId,
                title: title,
                url: url
            }, () => {
                // 重新加载当前文件夹
                loadBookmarks(folderId);
                // 关闭弹窗并重置表单
                dialog.classList.remove('show');
                form.reset();
            });
        } catch (e) {
            alert('请输入有效的URL地址！');
            urlInput.focus();
        }
    };
}

// 添加获取随机边框渐变色的函数
function getRandomBorderGradient() {
    const gradients = [
        'linear-gradient(45deg, #12c2e9, #c471ed, #f64f59)',
        'linear-gradient(45deg, #ee9ca7, #ffdde1)',
        'linear-gradient(45deg, #42275a, #734b6d)',
        'linear-gradient(45deg, #bdc3c7, #2c3e50)',
        'linear-gradient(45deg, #de6262, #ffb88c)',
        'linear-gradient(45deg, #06beb6, #48b1bf)',
        'linear-gradient(45deg, #eb3349, #f45c43)',
        'linear-gradient(45deg, #614385, #516395)',
        'linear-gradient(45deg, #02aab0, #00cdac)',
        'linear-gradient(45deg, #d66d75, #e29587)'
    ];
    return gradients[Math.floor(Math.random() * gradients.length)];
} 